package com.google.ant.extensions;

import java.io.File;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import com.google.ant.extensions.types.Module;
import com.google.ant.extensions.utils.IOUtils;
import org.apache.tools.ant.Project;

public class SourceRepo {
    private static final String DEP_SRC_LINK_REPO = "src-link.repo";
    private Map<String, Module> cache = new HashMap<String, Module>();
    
    private Project project;

    public SourceRepo() {
    }

    public SourceRepo(Project prj) {
        this();
        this.project = prj;
    }

    public File getSourceRepo() {
        String fantBase = System.getProperty("FANT_HOME");
        if (fantBase == null && project != null) {
            fantBase = project.getProperty("fant.etc.dir");
        }
        if (fantBase == null && project != null) {
            fantBase = project.getProperty("ant.home") + "/etc/fant";
        }
        if (fantBase != null) {
            System.setProperty("FANT_HOME", fantBase);
        } else {
            fantBase = System.getProperty("user.home") + "/etc/fant";
        }

        return new File(fantBase, DEP_SRC_LINK_REPO);
    }

    public void add(String line) {
        Module m = Module.parse(line);
        cacheAndAppend(line, m.getSignature(), m);
    }

    private void load() {
        Collection<String> lines  = IOUtils.getLines(getSourceRepo());
        for (String line : lines) {
            Module m = Module.parse(line);
            cache.put(m.getSignature(), m);
        }
    }

    public Module get(String key) {
        if (cache.isEmpty()) {
            load();
        }
        return cache.get(key);
    }

    public Collection<Module> get() {
        if (cache.isEmpty()) {
            load();
        }
        return cache.values();
    }

    public void add(final Module module) {
        String line = module.self();
        if (line != null) {
            cacheAndAppend(line, module.getSignature(), module);
        }
    }

    private void cacheAndAppend(String line, String key, Module module) {
        cache.put(key, module);
        IOUtils.appendLine(line, getSourceRepo());
    }
}